const qiniu = require('qiniu');
const accessKey = process.env.KODO_ACCESS_KEY;
const secretKey = process.env.KODO_SECRET_KEY;
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

const options = {
  scope: 'agents-bot-wechat',
  expires: 60 * 60 * 24 * 30 * 3,
};
const putPolicy = new qiniu.rs.PutPolicy(options);
const uploadToken = putPolicy.uploadToken(mac);

const config = new qiniu.conf.Config();
// 空间对应的区域，若不配置将自动查询
// config.regionsProvider = qiniu.httpc.Region.fromRegionId('qiniu.zone.Zone_z0');

const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

// 表单-单文件上传
function qiniuKodoPutFile( file, fileName) {
  return new Promise((resolve, reject) => {
    console.log('qiniuKodoPutFile', formUploader)
    // 文件上传
    formUploader.put(uploadToken, Date.now() + '_' + fileName, file, putExtra)
    .then(({ data, resp }) => {
        if (resp.statusCode === 200) {
          console.log('我成功', data)
          data.url = 'http://qiniu.yuanlj.top/' + data.key
          resolve(data)
        } else {
          console.log('我失败', data, resp)
          reject(data)
        }
    })
    .catch(err => {
      console.log(' 我failed', err);
    });
  })
}

module.exports = {
  qiniuKodoPutFile
};